package com.keke.study_app;

import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.Voice;

import java.util.HashSet;
import java.util.Locale;

public class MyReader {

    private static MyReader instance;
    private MyReader (){}

    public static MyReader getInstance() {
        if (instance == null) {
            instance = new MyReader();
        }
        return instance;
    }
    
    // TTS对象
    private TextToSpeech mTextToSpeech;

    public void speak(Context context, String tex) {
        if (mTextToSpeech == null) {
            initTextToSpeech(context, tex);
        } else if (!mTextToSpeech.isSpeaking()) {

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                System.out.println("开始朗读");
                int ok = mTextToSpeech.speak(tex, TextToSpeech.QUEUE_ADD, null, "first");
                System.out.println("开始朗读"+ok);
            }
            return ;
        } else {
            System.out.println("无法朗读");
        }
    }

    public void stop() {
        if (mTextToSpeech != null) {
            mTextToSpeech.stop();
        }
    }

    private void initTextToSpeech(Context context, String tex) {
        if (mTextToSpeech != null) {
            speak(context, tex);
            return;
        }
        mTextToSpeech = new TextToSpeech(context, speechListener(context, tex));
        mTextToSpeech.setPitch(1f);
        mTextToSpeech.setSpeechRate(1f);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Voice voice = hanleVoice();
            mTextToSpeech.setVoice(voice);
        }
    }

    private TextToSpeech.OnInitListener speechListener(Context context, String tex) {
        return new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
                if (TextToSpeech.SUCCESS == i) {
                    int result = mTextToSpeech.setLanguage(Locale.CHINA);
                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
                            && result != TextToSpeech.LANG_AVAILABLE){
                        System.out.println("TTS暂时不支持这种语音的朗读！");
                    } else {
                        speak(context, tex);
                    }
                } else {
                    System.out.println("失败");
                }
            }
        };
    }

    private Voice hanleVoice() {
        HashSet<String> set = new HashSet<>();
        set.add("hello");
        Voice voice = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            voice = new Voice("ceShi", Locale.CHINA, Voice.LATENCY_NORMAL, Voice.QUALITY_HIGH, false, set);
        }
        return voice;
    }
}
